package com.hourse.app.utils;

import com.hourse.platform.exception.AppException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;

//import net.coobird.thumbnailator.Thumbnails;
//import net.coobird.thumbnailator.geometry.Positions;

@Slf4j
//@Component
public class FileUtil {


    private static String filePath;

    private static String baseUrl;

    private static String rootDir;

    @Value("${baseUrl}")
    public void setBaseUrl(String baseUrl) {
        FileUtil.baseUrl = baseUrl;
    }

    @Value("${filePath}")
    public void setFilePath(String filePath) {
        FileUtil.filePath = filePath;
    }

    @Value("${direct.root}")
    public void setRootDir(String rootDir) {
        FileUtil.rootDir = rootDir;
    }

    /*
     * @功能描述: 【生成查看】
     * @作   者 : Jiang.yu
     * @创建时间 : 2020/12/6 11:11
     */
    public static String createViewUrl(String id) {
        if (id == null) return null;
        return new StringBuffer(baseUrl).append("common/view/").append(id).toString();
    }


    public static String createFinanceFileViewdUrl(String flow) {
        if (flow == null) return null;
        return new StringBuffer(baseUrl).append("common/viewFinanceFile/").append(flow).toString();
    }

    public static String createPingzhengViewdUrl(String id) {
        if (id == null) return null;
        return new StringBuffer(baseUrl).append("payforapplycash/view/").append(id).toString();
    }

    public static String createviewOwnBillTemplateUrl(String id) {
        if (id == null) return null;
        return new StringBuffer(baseUrl).append("financebillownsplit/viewOwnBillTemplateFile/").append(id).toString();
    }

    /**
     * 兑付凭证
     *
     * @param id
     * @return
     */
    public static String createCashingViewUrl(String id) {
        if (id == null) return null;
        return new StringBuffer(baseUrl).append("cashing/viewUrl/").append(id).toString();
    }

    /**
     * 项目评审下载
     *
     * @param id
     * @return
     */
    public static String createEvaluaTionViewUrl(String id) {
        if (id == null) return null;
        return new StringBuffer(baseUrl).append("evaluation/view/").append(id).toString();
    }

    /**
     * 项目评审下载
     *
     * @param id
     * @return
     */
    public static String createEvaluaFileViewUrl(String id) {
        if (id == null) return null;
        return new StringBuffer(baseUrl).append("evaluation/rowfile/view/").append(id).toString();
    }

    public static String createUserIconUrl(String id) {
        if (id == null) return null;
        return new StringBuffer(baseUrl).append("userRegister/view/").append(id).toString();
    }

    public static String createFinanceUplodFileViewdUrl(String id) {
        if (id == null) return null;
        return new StringBuffer(baseUrl).append("financeApply/viewLoanFile/").append(id).toString();
    }

    public static String createFinanceRepayFileViewUrl(String id) {
        if (id == null) return null;
        return new StringBuffer(baseUrl).append("financeApply/viewRepayFile/").append(id).toString();
    }

    /* 保存文件
     * @功能描述: 【】
     * @作   者 : Jiang.yu
     * @创建时间 : 2020/12/2 20:47
     */
    public static String saveToFile(MultipartFile file) throws Exception {


        String path = filePath + File.separator + "file" + DateUtil.DateToString("yyyyMMddSSS") + "-" + file.getOriginalFilename();

        File baseFilePath = new File(filePath + File.separator);

        if (!baseFilePath.exists())
            baseFilePath.mkdirs();


        //String suffix = path.split(".")[1];

        if (!path.endsWith(".jpg") &&
                !path.endsWith(".png") &&
                !path.endsWith(".jpeg")) {

            FileOutputStream out = new FileOutputStream(path);
            out.write(file.getBytes());
            out.close();

            return path;
        }
        /**加水印-开始*/
        String createTimeStr = DateUtil.DateToString("yyyy.MM.dd");
        String signStr = DateUtil.DateToString("专项债项目专用");
        // 1、源图片
        //new BufferedImage().
        Image srcImg = ImageIO.read(file.getInputStream());
        //Image srcImg = ImageIO.read(new File(path));
        BufferedImage buffImg = new BufferedImage(srcImg.getWidth(null), srcImg.getHeight(null), BufferedImage.TYPE_INT_RGB);
        // 2、得到画笔对象
        Graphics2D g = buffImg.createGraphics();
        // 3、设置对线段的锯齿状边缘处理
        g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
        g.drawImage(srcImg.getScaledInstance(srcImg.getWidth(null), srcImg.getHeight(null), java.awt.Image.SCALE_SMOOTH), 0, 0, null);

        // 5、设置水印文字颜色
        g.setColor(Color.LIGHT_GRAY);
        // 6、设置水印文字Font
        g.setFont(new java.awt.Font("宋体", java.awt.Font.BOLD, buffImg.getWidth() / 50));
        // 7、设置水印文字透明度
        g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP, 0.35f));
        // 8、第一参数->设置的内容，后面两个参数->文字在图片上的坐标位置(x,y)
        //g.drawString(createTimeStr, buffImg.getWidth() / 6, buffImg.getHeight() / 100 * 97 );
        //g.drawString(createTimeStr, buffImg.getWidth() / 6, buffImg.getHeight() / 100 * 97 );
        int iw = buffImg.getWidth() / 5;
        int ih = buffImg.getHeight() / 7;
        for (int i = 0; i < 5; i++) {
            for (int k = 0; k < 13; k++) {
                if (k % 2 == 0)
                    if (i % 2 == 1)
                        g.drawString(createTimeStr, i * iw, k * ih);
                    else
                        g.drawString(signStr, i * iw, k * ih);
                else if (i % 2 == 1)
                    g.drawString(createTimeStr, (int) ((i - 0.5) * iw), k * ih);
                else
                    g.drawString(signStr, (int) ((i - 0.5) * iw), k * ih);

            }
        }
        // 9、释放资源
        g.dispose();
        // 10、生成图片
        FileOutputStream out = new FileOutputStream(path);
        out = new FileOutputStream(path);
        ImageIO.write(buffImg, "jpg", out);
        out.close();

        /**加水印-结束*/

       /* FileOutputStream out = new FileOutputStream(path);
        out.write(file.getBytes());
        out.close();*/

        return path;
    }

    /**
     * 保存文件到磁盘
     *
     * @param baseStr
     * @param orderCode
     * @return
     */
    public static int saveToFile(String baseStr, String path, String orderCode) throws Exception {

        //InputStream is = null;
        OutputStream os = null;
        try {
            //写入文件
            //Base64Utils.decoderBase64File(baseStr, path);

           /* if(baseStr.indexOf("base64,") > -1){
                baseStr = baseStr.split("base64,")[1];
            }*/
            //加日期水印
            String createTimeStr = DateUtil.DateToString("yyyy-MM-dd");
            // 1、源图片
            Image srcImg = ImageIO.read(new File(path));
            BufferedImage buffImg = new BufferedImage(srcImg.getWidth(null), srcImg.getHeight(null), BufferedImage.TYPE_INT_RGB);
            // 2、得到画笔对象
            Graphics2D g = buffImg.createGraphics();
            // 3、设置对线段的锯齿状边缘处理
            g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
            g.drawImage(srcImg.getScaledInstance(srcImg.getWidth(null), srcImg.getHeight(null), Image.SCALE_SMOOTH), 0, 0, null);

            // 5、设置水印文字颜色
            g.setColor(Color.WHITE);
            // 6、设置水印文字Font
            g.setFont(new Font("宋体", Font.BOLD, buffImg.getWidth() / 10));
            // 7、设置水印文字透明度
            g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP, 0.95f));
            // 8、第一参数->设置的内容，后面两个参数->文字在图片上的坐标位置(x,y)
            g.drawString(createTimeStr, buffImg.getWidth() / 6, buffImg.getHeight() / 100 * 97);
            // 9、释放资源
            g.dispose();
            // 10、生成图片
            os = new FileOutputStream(path);
            ImageIO.write(buffImg, "jpg", os);
            os.close();


        } catch (IOException e) {
            e.printStackTrace();
            throw e;
        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        }


        return 1;
    }

    public static void deleteFile(File srcDir) {

        for (File file : srcDir.listFiles()) {
            if (file.isDirectory()) {
                deleteFile(file);
            } else {
                log.info("正在删除文件" + file.getPath() + "....");
                file.delete();
            }
        }
        log.info("正在目录删除" + srcDir.getPath() + "....");
        srcDir.delete();
    }


    /**
     * 文件下载方法
     *
     * @param response
     * @param filePath
     * @param encode
     */
   /* public static void download(HttpServletResponse response, String filePath, String encode) {
        response.setContentType("text/html;charset=" + encode);
        BufferedInputStream bis = null;
        BufferedOutputStream bos = null;
        String downLoadPath = filePath;
        try {
            File file = new File(downLoadPath);
            long fileLength = file.length();
            String fileName = file.getName();
            response.setContentType("application/x-msdownload;");
            response.setHeader("Content-disposition", "attachment; filename=" + new String(fileName.getBytes(encode), "ISO8859-1"));
            response.setHeader("Content-Length", String.valueOf(fileLength));
            bis = new BufferedInputStream(new FileInputStream(downLoadPath));
            bos = new BufferedOutputStream(response.getOutputStream());
            byte[] buff = new byte[2048];
            int bytesRead;
            while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
                bos.write(buff, 0, bytesRead);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (bis != null)
                try {
                    bis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            if (bos != null)
                try {
                    bos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
        }
    }*/


    /**
     * 以流的方式下载
     *
     * @param response
     * @param filePath loadType 1 page 2 down
     * @param encode
     * @return response
     */
    public static HttpServletResponse downloadStream(HttpServletResponse response, String filePath, String encode) throws AppException {
        return downloadStream(response, filePath, encode, null);
    }

    public static HttpServletResponse downloadStream(HttpServletResponse response, String filePath, String encode, String loadType) throws AppException {
        response.setContentType("text/html;charset=" + encode);
        try {

            if(rootDir.equals("C:/Users/Administrator/Desktop/financebill/")){
                filePath = filePath.replace("/opt/jarprocess/charging/zxz_files/","C:/Users/Administrator/Desktop/financebill/");
            }
            // path是指欲下载的文件的路径
            File file = new File(filePath);
            // 取得文件名
            String filename = file.getName();
            // 取得文件的后缀名
            // String ext = filename.substring(filename.lastIndexOf(".") + 1).toUpperCase();
            // 以流的形式下载文件
            InputStream fis = new BufferedInputStream(new FileInputStream(filePath));
            byte[] buffer = new byte[fis.available()];
            fis.read(buffer);
            fis.close();
            // 清空response
            response.reset();
            // 设置response的Header
            if ("2".equals(loadType)) {
                response.addHeader("Content-Disposition", "attachment;filename=" + new String(filename.getBytes(encode), "ISO8859-1"));
            }
            response.addHeader("Content-Length", "" + file.length());
            OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
            response.setContentType("application/octet-stream");
            toClient.write(buffer);
            toClient.flush();
            toClient.close();
        } catch (IOException ex) {
            ex.printStackTrace();
            throw new AppException("Open file error! File is not exist!");
        }
        return response;
    }


    /**
     * @param urlPath      http地址
     * @param fileNamePath 本在保存地址
     * @return
     */
    public boolean downloadFromHttp(String urlPath, String fileNamePath) {
        try {

            URL url = new URL(urlPath);

            HttpURLConnection connection = (HttpURLConnection) url.openConnection();

            DataInputStream in = new DataInputStream(connection.getInputStream());

            DataOutputStream out = new DataOutputStream(new FileOutputStream(fileNamePath));

            byte[] buffer = new byte[4096];

            int count = 0;

            while ((count = in.read(buffer)) > 0) {
                out.write(buffer, 0, count);
            }

            out.close();

            in.close();

            return true;

        } catch (Exception e) {
            return false;
        }

    }


}
